<script setup lang="ts">
import { useTemplateRef } from 'vue';

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

const defaultData = {
  id: '',
  username: '',
  nickname: '',
  sex: '',
  status: '',
  mobile: '',
  role: '',
};

const visible = defineModel<boolean>({ required: true });
const formData = ref({ ...defaultData } as any);

const formRef = useTemplateRef('formRef');

const handleOpen = () => {
  formData.value = props.data.id ? { ...props.data } : { ...defaultData };
};
const handleClose = () => {
  formRef.value?.resetFields();
};

const handleSubmit = async () => {
  await formRef.value?.validate();
  ElMessage.success('操作成功');
  visible.value = false;
};

const title = computed(() => (!!props.data?.id ? '编辑用户' : '新增用户'));
</script>

<template>
  <el-dialog v-model="visible" :title="title" width="500" append-to-body @open="handleOpen" @close="handleClose">
    <el-form ref="formRef" :model="formData" :label-width="100">
      <el-form-item
        label="名称"
        prop="username"
        :rules="{ required: true, message: '名称必填', trigger: ['change', 'blur'] }"
      >
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="formData.sex">
          <el-option value="1">男</el-option>
          <el-option value="2">女</el-option>
          <el-option value="0">保密</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="formData.status" active-value="1" inactive-value="0" />
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input v-model="formData.mobile" />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-radio-group v-model="formData.role">
          <el-radio value="1">超级管理员</el-radio>
          <el-radio value="2">管理员</el-radio>
          <el-radio value="3">开发</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
